<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/resources/layui/css/layui.css">
    <script type="text/javascript" src="${pageContext.request.contextPath}/resources/layui/layui.js"></script>
</head>
<body>
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
    <legend>常规使用：普通图片上传</legend>
</fieldset>

<div class="layui-upload">
    <button type="button" class="layui-btn" id="test1">选择图片</button>
    <div class="layui-upload-list">
        <img class="layui-upload-img" id="demo1" src="${pageContext.request.contextPath}/${user.img}" onerror="javascript:this.src='${pageContext.request.contextPath}/resources/img/deault.jpg'" width="200px" height="200px">
        <p id="demoText"></p>
    </div>
    <button type="button" class="layui-btn" id="uploadBtn">上传图片</button>
</div>
</body>
<script type="text/javascript">
    layui.use(['jquery','upload'],function () {
        var $ = layui.jquery;
        var upload = layui.upload;

        //普通图片上传
        var uploadInst = upload.render({
            elem: '#test1',
            url: '${pageContext.request.contextPath}/su.do?service=modifyImg', //改成您自己的上传接口modifyImg
            field: "fileImg", //自定义文件域的name值
            accept: "images",//允许上传的文件类型
            acceptMime: 'image/*',//文件选择框支持的类型
            exts: "jpg|png|gif|bmp|jpeg",//允许上传的文件的后缀
            auto: false,//不自动上传
            bindAction: "#uploadBtn",//触发文件上传动作
            field: "fileImg",//自定义文件域的name值
            //size:50,//允许上传的文件的最大字节数
            drag: true,//允许拖拽上传
            choose: function(obj){
                //预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result){
                    $('#demo1').attr('src', result); //图片链接（base64）
                });
            }
            ,done: function(res){
                //如果上传失败
                if(res.code == 200){
                    var data = res.data;//图片的网络路径
                    //为main.jsp 页面的图像赋值
                    parent.document.getElementById("userPhoto").src = "${pageContext.request.contextPath}" + "/" + data;
                }else{
                    return layer.msg('上传失败');
                }
                //上传成功
            }
            ,error: function(){
                //演示失败状态，并实现重传
                var demoText = $('#demoText');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function(){
                    uploadInst.upload();
                });
            }
        });
    })
</script>
</html>
